﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace UtilLib
{
    public static class Util
    {
        /// <summary>
        /// Encrypts a string using the SHA256 algorithm.
        /// </summary>
        /// <param name="plainMessage">
        /// The plain Message.
        /// </param>
        /// <returns>
        /// The hash password.
        /// </returns>
        public static string HashPassword(string plainMessage)
        {
            var data = Encoding.UTF8.GetBytes(plainMessage);
            using (HashAlgorithm sha = new SHA256Managed())
            {
                sha.TransformFinalBlock(data, 0, data.Length);
                return Convert.ToBase64String(sha.Hash);
            }
        }

        /// <summary>
        /// Generates random password for password reset
        /// </summary>
        /// <returns>
        /// Random password
        /// </returns>
        public static string RandomPassword()
        {
            var chars = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
            var password = string.Empty;
            var random = new Random();

            for (var i = 0; i < 8; i++)
            {
                var x = random.Next(1, chars.Length);
                if (!password.Contains(chars.GetValue(x).ToString()))
                {
                    password += chars.GetValue(x);
                }
                else
                {
                    i--;
                }
            }

            return password;
        }

        private static readonly Regex emailRegex = new Regex(@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                                        + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				                                            [0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
                                        + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				                                            [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                                        + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$");


        /// <summary>
        /// Validates an email address. Returns true if the string is a valid formatted email address.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsEmailValid(string email)
        {
            // Null check needs to be had because RegEx
            // doesn't accept null parameters.
            if (!StringUtil.IsNullOrWhitespace(email))
            {
                return emailRegex.IsMatch(email);
            }

            return false;
        }

        public static string ToString(object obj)
        {
            string ret;
            try
            {
                StringBuilder objectText = new StringBuilder();
                PropertyInfo[] properties = obj.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    string _name = property.Name;
                    try
                    {
                        string _value = property.GetValue(obj, null).ToString();
                        objectText.Append(_name + "=" + _value + "|");
                    }
                    catch
                    {
                        objectText.Append(_name + "=?" + property.PropertyType.ToString() + "|");
                    }

                }

                ret = "{" + objectText.ToString() + "}";
            }
            catch
            {
                ret = obj.ToString();
            }

            return ret;
        }

        /// <summary>
        ///     Occurs when a message will be logged. The sender is a string containing the log message.
        /// </summary>
        public static event EventHandler<LogEventArgs> OnLog;

        /// <summary>
        /// Sends a message to any subscribed log listeners.
        /// </summary>
        /// <param name="message">
        /// The message to be logged.
        /// </param>
        public static void Log(LogLevel level,Exception exception)
        {
            if (OnLog != null)
            {
                OnLog(exception, new LogEventArgs(level, exception));
            }
        }

        #region WorkItem
        //public static string WorkItemCollectionDetails(Microsoft.Practices.CompositeUI.WorkItem workItem)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.AppendLine("ITEMS:");
        //    Microsoft.Practices.CompositeUI.Collections.ManagedObjectCollection<object> coll = workItem.Items;
        //    coll.ToList().ForEach(k => sb.AppendLine(k.ToString()));

        //    Microsoft.Practices.CompositeUI.Collections.ManagedObjectCollection<object> sp = workItem.SmartParts;
        //    sp.ToList().ForEach(k => sb.AppendLine(k.ToString()));

        //    sb.AppendLine("WORKSPACES:");
        //    Microsoft.Practices.CompositeUI.Collections.ManagedObjectCollection<Microsoft.Practices.CompositeUI.SmartParts.IWorkspace> ws = workItem.Workspaces;
        //    ws.ToList().ForEach(k =>
        //        {
        //            Microsoft.Practices.CompositeUI.SmartParts.IWorkspace workspace = k.Value;
        //            sb.AppendLine(k.ToString());
        //            sb.AppendLine(" SMARTPARTS:");
        //            workspace.SmartParts.ToList().ForEach(x => sb.AppendLine(" " + x.ToString()));
        //        });

        //    return sb.ToString();
        //}
        #endregion


    }
}
